using System;
using System.Net;
using System.Threading;
using Game500.ClientServerCommon.Src;
using Game500.StServer.Src;

namespace MtServer.Src
{
  internal class SessionThread
  {
    private const int MinPort = 1000;
    private const int MaxPort = 10000;
    private readonly IPAddress myAddress;
    private readonly Server myServer;
    private readonly ManualResetEvent myServerStartEvent = new ManualResetEvent(false);
    private readonly Thread myThread;
    private Action myOnEndAction;

    public SessionThread(Guid mapId, string gameMessage, BaseMapManager mapManager, IPAddress address)
    {
      myAddress = address;
      myThread = new Thread(ThreadProc);
      myThread.Name = "SessionThread";
      myServer = new Server(mapId, gameMessage, mapManager);
      if (!myServer.TryBind(MinPort, MaxPort)) throw new Exception("Unable to bind new port at given range. Extend range");
    }

    public NetworkGameInfo GameInfo
    {
      get
      {
        myServer.GameInfo.ServerAddress.Address = myAddress;
        return myServer.GameInfo;
      }
    }

    private void ThreadProc()
    {
      myServer.Initialize();
      myServerStartEvent.Set();
      myServer.Run();
      if (myOnEndAction != null) myOnEndAction();
    }

    public void Initialize(Action onStart, Action onEnd)
    {
      if (onStart != null) onStart();
      myOnEndAction = onEnd;
      myThread.Start();
      myServerStartEvent.WaitOne();
    }
  }
}